package org.mclll.xwangplugin.town.command.executor;

import com.alibaba.fastjson.JSONArray;
import com.google.common.collect.Lists;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mclll.xwangplugin.town.database.domain.TownDO;
import org.mclll.xwangplugin.town.database.domain.TownPlayerDO;
import org.mclll.xwangplugin.town.database.mapper.manage.TownManage;
import org.mclll.xwangplugin.town.database.mapper.manage.TownPlayerManage;
import org.mclll.xwangplugin.town.enums.PlayerTownIdentity;
import org.mclll.xwangplugin.town.enums.TownLevel;
import org.mclll.xwangplugin.town.enums.TownParty;
import org.mclll.xwangplugin.town.lp.LuckPermsTown;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.mclll.xwangplugin.town.config.TownContext.*;
import static org.mclll.xwangplugin.util.PlayerTools.*;

/**
 * @author: geduo
 * @date: 2023/9/23 19:31
 */
public class CreateTownExecutor {

    public static void createNewTown(CommandSender sender, String[] args) {
        // poitown createNewTown <城镇名> <城镇阵营> <领地列表> <镇长名称>
        UUID townUuid = UUID.randomUUID();
        if (args.length < 5) {
            sender.sendMessage(CREATE_NEW_TOWN_COMMAND_FORMAT);
            return;
        }
        if (args.length != 5) {
            return;
        }
        String townName = args[1].trim();
        TownDO checkParam = new TownDO();
        checkParam.setName(townName);
        List<TownDO> checkTown = TownManage.selectList(checkParam);
        if (!checkTown.isEmpty()) {
            sender.sendMessage(String.format(TOWN_NAME_IS_ALREADY_EXIST, townName));
            return;
        }
        TownParty townParty = null;
        try {
            townParty = TownParty.valueOf(args[2]);
        } catch (IllegalArgumentException e) {
            sender.sendMessage(TOWN_PARTY_NOT_FOUND);
            return;
        }
        String resListStr = args[3];
        String checkResult = checkRes(resListStr);
        if (checkResult != null) {
            sender.sendMessage(String.format(RES_IS_REGISTERED, checkResult));
            return;
        }
        List<String> resList = Arrays.asList(resListStr.split(","));
        String leaderName = args[4].trim();
        TownPlayerDO playerParam = new TownPlayerDO();
        String leaderUuid = "";
        playerParam.setName(leaderName);
        List<TownPlayerDO> townPlayerList = TownPlayerManage.selectList(playerParam);
        if (!townPlayerList.isEmpty()) {
            playerParam = townPlayerList.get(0);
            leaderUuid = playerParam.getUuid();
            if (playerParam.getIdentity() == PlayerTownIdentity.LEADER) {
                sender.sendMessage(PLAYER_IS_ALREADY_LEADER);
                return;
            }
            playerParam.setIdentity(PlayerTownIdentity.LEADER);
            playerParam.setTownUuid(townUuid.toString());
            TownPlayerManage.updateByUuid(playerParam);
        }
        OfflinePlayer player = getOfflineOrOnlinePlayerByUuid(leaderUuid);
        TownDO townParam = new TownDO();
        townParam.setUuid(townUuid.toString());
        townParam.setName(townName);
        townParam.setLeaderUuid(playerParam.getUuid());
        // 镇长权限
        LuckPermsTown.addLeader(playerParam.getName());
        townParam.setTownParty(townParty);
        townParam.setTownLevel(TownLevel.I);
        townParam.setMonthTax(0);
        townParam.setLastTaxTime(LocalDateTime.now());
        townParam.setLeaderLastSubsidyTime(LocalDateTime.now());
        townParam.setResList(JSONArray.toJSONString(resList));
        TownManage.insert(townParam);
        // 城镇权限
        LuckPermsTown.creteTown(townName, townParty);
        LuckPermsTown.addPlayerToTown(townName, Collections.singletonList(playerParam.getName()));

        sender.sendMessage(String.format(CREATE_NEW_TOWN_SUCCESS, townName));
        if (player.isOnline()) {
            ((Player) player).sendMessage(String.format(CREATE_NEW_TOWN_SUCCESS_SEND_LEADER, townName));
        }
    }

    public static List<String> createNewTownTabComplete(CommandSender sender, String[] args) {
        // 格式为：poitown createNewTown <城镇名> <城镇阵营> <领地列表> <镇长名称>
        switch (args.length) {
            case 2:
                return Collections.singletonList("<城镇名>");
            case 3:
                return Arrays.stream(TownParty.values()).map(Enum::name).collect(Collectors.toList());
            case 4:
                return Collections.singletonList("<领地列表:多个使用逗号分割>");
            default:
                return null;
        }
    }

    private static String checkRes(String resName) {
        List<TownDO> townList = TownManage.selectList(null);
        List<String> resList = Lists.newArrayList();
        for (TownDO town : townList) {
            // gson把json转数组
            resList.addAll(JSONArray.parseArray(town.getResList(), String.class));
        }
        for (String res : resName.split(",")) {
            if (resList.contains(res)) {
                return res;
            }
        }
        return null;
    }
}
